<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>我的灵感仓库 - 云端同步版</title>
    <style>
        /* 样式部分保持不变，确保界面美观和功能完整 */
        * { margin: 0; padding: 0; box-sizing: border-box; }
        body { 
            font-family: 'Microsoft YaHei', sans-serif; 
            max-width: 800px; 
            margin: 0 auto; 
            padding: 20px; 
            background: #f5f5f5; 
        }
        .header { 
            background: white; 
            padding: 30px; 
            border-radius: 10px; 
            box-shadow: 0 2px 10px rgba(0,0,0,0.1); 
            margin-bottom: 20px; 
            text-align: center; 
        }
        .nav { 
            display: flex; 
            gap: 15px; 
            margin: 20px 0; 
            flex-wrap: wrap;
        }
        .nav a { 
            padding: 10px 20px; 
            background: #4CAF50; 
            color: white; 
            text-decoration: none; 
            border-radius: 5px; 
            cursor: pointer;
        }
        .idea-card { 
            background: white; 
            padding: 20px; 
            margin: 15px 0; 
            border-radius: 8px; 
            box-shadow: 0 1px 5px rgba(0,0,0,0.1); 
            position: relative;
        }
        .delete-btn {
            position: absolute;
            top: 10px;
            right: 10px;
            background: #ff4757;
            color: white;
            border: none;
            padding: 5px 10px;
            border-radius: 3px;
            cursor: pointer;
        }
        .tags { 
            margin: 10px 0; 
        }
        .tag { 
            display: inline-block; 
            background: #e3f2fd; 
            padding: 3px 8px; 
            border-radius: 3px; 
            font-size: 12px; 
            margin-right: 5px; 
        }
        form { 
            background: white; 
            padding: 20px; 
            border-radius: 8px; 
        }
        input, textarea { 
            width: 100%; 
            padding: 10px; 
            margin: 8px 0; 
            border: 1px solid #ddd; 
            border-radius: 4px; 
        }
        button { 
            background: #4CAF50; 
            color: white; 
            padding: 12px 25px; 
            border: none; 
            border-radius: 5px; 
            cursor: pointer; 
        }
        .sync-status {
            padding: 10px;
            margin: 10px 0;
            border-radius: 5px;
            text-align: center;
        }
        .syncing { background: #fff3cd; color: #856404; }
        .synced { background: #d1ecf1; color: #0c5460; }
        .error { background: #f8d7da; color: #721c24; }
    </style>
</head>
<body>
    <div class="header">
        <h1>💡 我的灵感仓库</h1>
        <p>云端同步版 - 多设备实时同步</p>
        <div id="syncStatus" class="sync-status"></div>
    </div>

    <div class="nav">
        <a onclick="showSection('all-ideas')">所有灵感</a>
        <a onclick="showSection('submit-idea')">提交灵感</a>
        <a onclick="manualSync()">手动同步</a>
    </div>

    <div id="all-ideas" class="section">
        <h2>所有灵感记录</h2>
        <div id="ideasContainer">
            <!-- 灵感列表将动态加载在这里 -->
        </div>
    </div>

    <div id="submit-idea" class="section" style="display:none;">
        <h2>提交新灵感</h2>
        <form id="ideaForm">
            <input type="text" id="title" placeholder="灵感标题" required>
            <textarea id="content" placeholder="详细描述你的灵感..." rows="6" required></textarea>
            <input type="text" id="tags" placeholder="标签（用逗号分隔，如：科技,生活,创意）">
            <button type="submit">保存并同步</button>
        </form>
    </div>

    <script>
        // === 配置区：需要你根据实际情况修改 ===
        // 你的Gitee用户名（不是昵称，是个性地址）
        const GITEE_OWNER = 'srjpworld';
        // 你的仓库名称
        const GITEE_REPO = '灵感收集';
        // 你在Gitee设置的私人令牌（Private Token）
        const GITEE_TOKEN = '43fdad760f2b2c4d367eba64869e2818';
        // ================================

        // 页面切换
        function showSection(sectionId) {
            document.querySelectorAll('.section').forEach(section => {
                section.style.display = 'none';
            });
            document.getElementById(sectionId).style.display = 'block';
            if (sectionId === 'all-ideas') {
                loadFromCloud(); // 显示所有灵感时从云端加载
            }
        }

        // 更新同步状态显示
        function updateSyncStatus(message, type = 'synced') {
            const statusEl = document.getElementById('syncStatus');
            statusEl.textContent = message;
            statusEl.className = `sync-status ${type}`;
        }

        // 手动同步
        async function manualSync() {
            updateSyncStatus('正在同步数据...', 'syncing');
            await loadFromCloud();
        }

        // 从Gitee Issues加载灵感
        async function loadFromCloud() {
            // 如果未正确配置，提示用户
            if (!GITEE_TOKEN || GITEE_OWNER === 'YOUR_GITEE_USERNAME') {
                updateSyncStatus('请先配置Gitee信息', 'error');
                return;
            }

            try {
                const response = await fetch(`https://gitee.com/api/v5/repos/${GITEE_OWNER}/${GITEE_REPO}/issues?state=open&sort=created&direction=desc&per_page=100`);
                if (!response.ok) {
                    throw new Error('网络响应异常');
                }
                const issues = await response.json();
                
                const ideas = issues.map(issue => ({
                    id: issue.id,
                    title: issue.title,
                    content: issue.body.replace(/标签:.*?\n\n/, ''), // 移除标签部分
                    tags: issue.labels ? issue.labels.map(label => label.name) : [],
                    date: issue.created_at.split('T')[0]
                }));

                displayIdeas(ideas);
                updateSyncStatus(`已同步 ${ideas.length} 条灵感`, 'synced');
            } catch (error) {
                console.error('从云端加载失败:', error);
                updateSyncStatus('同步失败: ' + error.message, 'error');
            }
        }

        // 显示灵感列表
        function displayIdeas(ideas) {
            const ideasContainer = document.getElementById('ideasContainer');
            
            if (!ideas || ideas.length === 0) {
                ideasContainer.innerHTML = '<p>还没有任何灵感记录，快去添加第一个吧！</p>';
                return;
            }

            ideasContainer.innerHTML = ideas.map(idea => `
                <div class="idea-card">
                    <h3>${escapeHtml(idea.title)}</h3>
                    <div class="tags">
                        ${(idea.tags || []).map(tag => `<span class="tag">${escapeHtml(tag)}</span>`).join('')}
                    </div>
                    <p>${escapeHtml(idea.content)}</p>
                    <small>创建时间: ${idea.date || '未知'}</small>
                </div>
            `).join('');
        }

        // 特殊字符转义，防止XSS
        function escapeHtml(unsafe) {
            if (!unsafe) return '';
            return unsafe
                .replace(/&/g, "&amp;")
                .replace(/</g, "&lt;")
                .replace(/>/g, "&gt;")
                .replace(/"/g, "&quot;")
                .replace(/'/g, "&#039;");
        }

        // 保存灵感到Gitee Issues
        document.getElementById('ideaForm').addEventListener('submit', async function(e) {
            e.preventDefault();
            
            const title = document.getElementById('title').value;
            const content = document.getElementById('content').value;
            const tags = document.getElementById('tags').value.split(',').map(tag => tag.trim()).filter(tag => tag);

            if (!GITEE_TOKEN || GITEE_OWNER === 'YOUR_GITEE_USERNAME') {
                updateSyncStatus('错误：请先配置Gitee信息', 'error');
                return;
            }

            updateSyncStatus('正在保存到云端...', 'syncing');

            try {
                const response = await fetch(`https://gitee.com/api/v5/repos/${GITEE_OWNER}/${GITEE_REPO}/issues`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({
                        title: title,
                        body: `标签: ${tags.join(',')}\n\n${content}`,
                        labels: tags.join(',')
                    })
                });
                
                if (!response.ok) {
                    const err = await response.json();
                    throw new Error(err.message || '保存失败');
                }

                updateSyncStatus('灵感保存成功！', 'synced');
                this.reset(); // 清空表单
                
                // 显示所有灵感页面
                showSection('all-ideas');
            } catch (error) {
                console.error('保存到云端失败:', error);
                updateSyncStatus('保存失败: ' + error.message, 'error');
            }
        });

        // 页面加载完成后显示所有灵感
        window.addEventListener('load', () => {
            showSection('all-ideas');
        });
    </script>
</body>
</html>